#include "sylar/sylar.h"


sylar::Logger::LoggerPtr g_logger = SYLAR_LOG_ROOT();

void run_in_fiber()
{
    SYLAR_LOG_INFO(g_logger) << "run_in_fiber  begin" << std::endl;
    //sylar::Fiber::GetThis()->swapOut(); // 协程挂起
   // sylar::Fiber::YaildToHold();
   sylar::Fiber::GetThis()->back();
    SYLAR_LOG_INFO(g_logger) << "run_in_fiber after end" << std::endl;
}
// main fiber
// run_in_fiber begin               ( swapIn  切换到当前协程执行)
// fiber after swapIn()             ( YaildToHold  协程挂起)
// run_in_fiber after end           ( swapIn )
// fiber after  end                 (协程执行结束)

void test_fiber()
{
    sylar::Fiber::GetThis();
    SYLAR_LOG_INFO(g_logger) << "main fiber " << std::endl;
    {
        sylar::Fiber::ptr fiber(new sylar::Fiber(run_in_fiber, 0));
       // fiber->swapIn();    // 协程启动 调用 run_in_fiber 
        fiber->call();
        SYLAR_LOG_INFO(g_logger) << "fiber after swapIn() " << std::endl;
        //fiber->swapIn();    // 协程再次启动
        fiber->call();
        SYLAR_LOG_INFO(g_logger) << "fiber after  end " << std::endl;
    }
    SYLAR_LOG_INFO(g_logger) << "fiber after  end2 " << std::endl;
}

int main(int argc, char* agrv[])
{
    sylar::Thread::SetName("main");
    std::vector<sylar::Thread::Ptr> vec;
    for (int i =0; i < 1; i++)
    {
        sylar::Thread::Ptr ptr (new sylar::Thread(test_fiber, "thread_" + std::to_string(i)));
        vec.push_back(ptr);
    }

    for (auto& i : vec)
    {
        i->join();
    }


    return 0;
}